<template> 
  <div>
    <el-upload
      ref="uploadImg"
      :action="ImgServiceUrl"
      :headers="uploadImg.headers"
      list-type="picture-card"
      :on-change="uploadImgChange"
      :http-request="handleUploadImg"
      :before-remove="handleRemoveImg"
      :file-list="fileList"
      :limit="maxCount"
    >
      <i class="el-icon-plus"></i>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>
<script>
  import {policy} from '@/api/oss';
  import { getToken } from "@/utils/auth";
  import {uploadFile} from "@/api/common/common";

  export default {
    name: 'multiUpload',
    props: {
      //图片属性数组
      value: Array,
      //最大上传图片数量
      maxCount:{
        type:Number,
        default:5
      }
    },
    data() {
      return {
        dataObj: {
          policy: '',
          signature: '',
          key: '',
          ossaccessKeyId: '',
          dir: '',
          host: ''
        },
        dialogVisible: false,
        dialogImageUrl:null,
        useOss:false, //使用oss->true;使用MinIO->false
        ossUploadUrl:'http://macro-oss.oss-cn-shenzhen.aliyuncs.com',
        minioUploadUrl:'http://localhost:8080/minio/upload',
        ImgServiceUrl: process.env.BASE_API + '/minio/upload',
        uploadImg: {
          // 是否显示弹出层（用户导入）
          open: false,
          // 弹出层标题（用户导入）
          title: "",
          // 是否禁用上传
          isUploading: false,
          // 是否更新已经存在的用户数据
          updateSupport: 0,
          // 设置上传的请求头部
          headers: { Authorization: "Bearer " + getToken() },
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + "/minio/upload"
        },
        form: {logo: null},
        logoFile: undefined,

      };
    },
    /*computed: {
      fileList() {
        let fileList=[];
        for(let i=0;i<this.value.length;i++){
          fileList.push({url:this.value[i]});
        }
        return fileList;
      }
    },*/
    created() {
      this.init();
    },
    methods: {
      init() {
        console.log('value----:' , this.value)
        let fileList=[];
        for(let i=0;i<this.value.length;i++){

          fileList.push({url:this.value[i]});
        }
        this.fileList = fileList;
      },
      uploadImgChange(file, fileList) {
        this.logoFile = file.raw;
      },
      /** 图片上传操作 */
      handleUploadImg(file, fileList) {
        let formData = new FormData();
        formData.append("file", this.logoFile);
        uploadFile('/minio/upload', formData).then(response => {
          if (response.code == 200) {
            this.form.logo = response.data.url;
            this.fileList.push({objId: response.data.objId, url:response.data.url, uid: file.file.uid});
            this.emitInput(this.fileList);
          }
        }).catch(err => {

        });
      },
      handleRemoveImg(file, fileList) {
        let index = this.fileList.findIndex(item => item.uid === file.uid);
        if (index > -1) {
          let objId = this.fileList[index].objId;
          this.fileList.splice(index, 1);

          this.$commonList(`/minio/delete/${objId}`, 'DELETE').then(res => {
            if (res.code == 200) {
              this.form.logo = undefined;
              this.$message.success("图片删除成功！");
              this.emitInput(this.fileList);
              return true
            } else {
              return false
            }
          }).catch(err => {
            return false
          })
        }
      },
      emitInput(fileList) {
        this.$emit('input', fileList)
      },
      handleRemove(file, fileList) {
        this.emitInput(fileList);
      },
      handlePreview(file) {
        this.dialogVisible = true;
        this.dialogImageUrl=file.url;
      },
      beforeUpload(file) {
        let _self = this;
        if(!this.useOss){
          //不使用oss不需要获取策略
          return true;
        }
        return new Promise((resolve, reject) => {
          policy().then(response => {
            _self.dataObj.policy = response.data.policy;
            _self.dataObj.signature = response.data.signature;
            _self.dataObj.ossaccessKeyId = response.data.accessKeyId;
            _self.dataObj.key = response.data.dir + '/${filename}';
            _self.dataObj.dir = response.data.dir;
            _self.dataObj.host = response.data.host;
            resolve(true)
          }).catch(err => {
            console.log(err)
            reject(false)
          })
        })
      },
      handleUploadSuccess(res, file) {
        let url = this.dataObj.host + '/' + this.dataObj.dir + '/' + file.name;
        if(!this.useOss){
          //不使用oss直接获取图片路径
          url = res.data.url;
        }
        this.fileList.push({name: file.name,url:url});
        this.emitInput(this.fileList);
      },
      handleExceed(files, fileList) {
        this.$message({
          message: '最多只能上传'+this.maxCount+'张图片',
          type: 'warning',
          duration:1000
        });
      },
    }
  }
</script>
<style>

</style>


